package com.geek.water.security;

import cn.hutool.json.JSONUtil;
import com.geek.water.constant.CodeConstant;
import com.geek.water.result.Result;
import com.geek.water.utils.WebUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/8/11
 */
@Component
public class SecurityHandler {

    //401认证失败
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint(){
        return new AuthenticationEntryPoint(){
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                Result result = new Result(CodeConstant.FAIL , authException.getMessage() , "401认证失败");
                WebUtils.renderString(response , JSONUtil.toJsonStr(result));
            }
        };
    }


    //403授权失败
    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                Result result = new Result(CodeConstant.FAIL , accessDeniedException.getMessage() , "403授权失败");
                WebUtils.renderString(response , JSONUtil.toJsonStr(result));
            }
        };
    }

}
